<?php
/**
 *  Module - Main Admin Pages.
 * @author  Philip Clarke royal@exploitingIT.co.uk
 * @copyright Copyright 2009 Bouncing Ltd t/a http://exploitingIT.co.uk
 * @copyright Copyright 2003-2007 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 */

  require('includes/application_top.php');

$fc = new smz_filesystem;

$fc->stat(DIR_FS_CATALOG_OVERLAYS);


$nozip = false;
if(!in_array('zip', get_loaded_extensions() ) ){
$nozip = true;
}


  if(isset($_FILES) && sizeof($_FILES)>0 && isset($_FILES['nof']) && !$fc->dnw && !$nozip){

    $fc->unlock(DIR_FS_CATALOG_OVERLAYS);
    $zip = new ZipArchive;
    if ($zip->open($_FILES['nof']['tmp_name']) === TRUE) {
	$zip->extractTo(DIR_FS_CATALOG_OVERLAYS);
	$zip->close();
	$messageStack->add_session('Install '.htmlentities(str_replace('.zip', '', $_FILES['nof']['name']), ENT_QUOTES).' completed.', 'success');
    } else {
	$messageStack->add_session('Failed to install '.htmlentities(str_replace('.zip', '', $_FILES['nof']['name']), ENT_QUOTES).'.', 'error');
    }
    $fc->relockRecursive(DIR_FS_CATALOG_OVERLAYS);

    header('Location: '.FILENAME_CSS_OVERLAY.'?page=files');
    exit;

  }


  if(isset($_GET['action']) && trim($_GET['action']) == 'upt'){

    $sql = "UPDATE template_select SET template_overlay='".mysql_escape_string($_GET['ov'])."' WHERE template_id='".(int)$_GET['tid']."'";

    $db->Execute($sql);

    $messageStack->add_session('Template overlay <em>\''.htmlentities($_GET['mn'], ENT_QUOTES).'\'</em> updated to <strong>\''.htmlentities($_GET['ov'], ENT_QUOTES).'\'</strong>.', 'success');

    header('Location: '.FILENAME_CSS_OVERLAY);
    exit;
  }

  $page = isset($_GET['page']) ? htmlentities($_GET['page'], ENT_QUOTES) : '' ;


// get an array of template info
  $dir = @dir(DIR_FS_CATALOG_TEMPLATES);
  $template_info = array();
  if (!$dir) die('DIR_FS_CATALOG_TEMPLATES NOT SET');
  while ($file = $dir->read()) {
    if (is_dir(DIR_FS_CATALOG_TEMPLATES . $file) && strtoupper($file) != 'CVS' && $file != 'template_default') {

      if (file_exists(DIR_FS_CATALOG_TEMPLATES . $file . '/template_info.php')) {
        require(DIR_FS_CATALOG_TEMPLATES . $file . '/template_info.php');
        $template_info[$file] = array('name' => $template_name,
                                      'version' => $template_version,
                                      'author' => $template_author,
                                      'description' => $template_description,
                                      'screenshot' => $template_screenshot,
				      'overlay_compatible' => isset($template_overlay_compatible) ? $template_overlay_compatible : false );
	unset($template_name, $template_version, $template_author, $template_description, $template_screenshot, $template_overlay_compatible);
      }
    }
  }
  $dir->close();

clearstatcache();

// get an array of overlay info

  $dir = @dir(DIR_FS_CATALOG_OVERLAYS);
  $overlay_info = array();
  if (!$dir) die('DIR_FS_CATALOG_OVERLAYS NOT SET');
  while ($file = $dir->read()) {
    if ( is_dir(DIR_FS_CATALOG_OVERLAYS . $file) && !in_array($file, array('.', '..') )  && (file_exists(DIR_FS_CATALOG_OVERLAYS.$file.'/jquery-ui-1.7.2.custom.css') || file_exists(DIR_FS_CATALOG_OVERLAYS.$file.'/jquery-ui.css') ) ) {
    if(file_exists(DIR_FS_CATALOG_OVERLAYS.$file.'/jquery-ui-1.7.2.custom.css')){
      $compatibility = '1.7.2';
    }else
    if(file_exists(DIR_FS_CATALOG_OVERLAYS.$file.'/jquery-ui.css')){
      $compatibility = 'default';
    }
	if(!isset($overlay_info[$compatibility])){
	  $overlay_info[$compatibility] = array();
	}
	$overlay_info[$compatibility][ DIR_FS_CATALOG_OVERLAYS.$file ] = $file;
    }
  }
  $dir->close();

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

function return_overlay_options($template_file, $current = ''){

   global $template_info, $overlay_info, $templates ;

// should be other way aroudn to catch cocks ups
//     print nl2br(print_r($template_info[$template_file], true)).' '.$template_file.'<br />';

    if(isset($template_info[$template_file]['overlay_compatible']) && is_array($template_info[$template_file]['overlay_compatible'])){

    $html = join(', ', $template_info[$template_file]['overlay_compatible']).'</td><td class="dataTableContent"><form action="'.FILENAME_CSS_OVERLAY.'" method="get" ><input type="hidden" name="action" value="upt" /><input type="hidden" name="tid" value="'. $templates->fields['template_id'].'" />';

    $html .= '<input type="hidden" value="'.htmlentities($template_info[$template_file]['name'], ENT_QUOTES).'" name="mn" />';

    $html .= '<select name="ov">';
      foreach($template_info[$template_file]['overlay_compatible'] as $possible_overlay){
	if(sizeof($overlay_info[$possible_overlay])>0){
	  foreach($overlay_info[$possible_overlay] as $overlay){
	    $selected = ($current == $overlay) ? ' selected ' : '';
	    $html .= '<option'.$selected.'>'.$overlay.'</option>';
	  }
	}
      }
    $html .= '</select></td>
                    <td class="dataTableContent" align="right">'.zen_image_submit('button_update.gif', IMAGE_UPDATE) ;
    return $html;

    }else{
    return 'Not overlay compatible.</td><td class="dataTableContent" colspan="2">
                    ' ;
    }

}

?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo HEADING_TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<link rel="stylesheet" type="text/css" href="includes/cssjsmenuhover.css" media="all" id="hoverJS">
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script type="text/javascript">
  <!--
  function init()
  {
    cssjsmenu('navbar');
    if (document.getElementById)
    {
      var kill = document.getElementById('hoverJS');
      kill.disabled = true;
    }
  }
  // -->
</script>
<style type="text/css">
  <!--

  a.wikilink1:link    { color:#009900; text-decoration:none }
  a.wikilink1:visited { color:#009900; text-decoration:none }
  a.wikilink1:hover   { color:#009900; text-decoration:underline }

  .bumrst{ font-weight: normal; font-size: 100%; }

  .adminbox{padding: 1em}

  -->
</style>
</head>
<body onload="init()">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->

<div>

<div style="float:left; padding: 8px 5px;">
<h1><?php echo HEADING_TITLE  ; ?></h1>
<?php
echo (defined('MODULE_RENAME_THIS_VERSION') ? 'version '.MODULE_RENAME_THIS_VERSION : '' );
?>
</div>

</div>

<div style="clear:both">

<ul style="background-color:#F5F5F5; border: solid #CCCCCC; border-width: 1px 0px;" class="toplinks">
  <li style="display:inline; padding:2px 5px; <?php echo ($page == '') ? 'background:#CCCCCC;' : ''; ?>">
    <a href="<?php echo zen_href_link(FILENAME_CSS_OVERLAY, '', 'SSL') ?>"><?php echo TEXT_LINK_TEMPLATE_OVERLAY ; ?></a>
  </li>
  <li style="display:inline; padding:2px 5px; <?php echo ($page == 'files') ? 'background:#CCCCCC;' : ''; ?>">
    <a href="<?php echo zen_href_link(FILENAME_CSS_OVERLAY, 'page=files', 'SSL') ?>"><?php echo TEXT_LINK_TEMPLATE_OVERLAY_FM ; ?></a>
  </li>
  <li style="display:inline; padding:2px 5px; <?php echo ($page == 'help') ? 'background:#CCCCCC;' : ''; ?>">
    <a href="<?php echo zen_href_link(FILENAME_CSS_OVERLAY, 'page=help', 'SSL') ?>">Help</a>
  </li>
</ul>

<?php

switch($page){
case 'upload':
?>
<div class="adminbox">

<?
break;
case 'overview':
?>
<div class="adminbox">
	<h2>Overview.</h2>

<?php
break;
case 'files':


?>
<div class="adminbox">
  <h2><?php echo TEXT_TITLE_TEMPLATE_OVERLAY_FM ; ?></h2>
  <h3><em><?php echo DIR_FS_CATALOG_OVERLAYS ; ?></em> status.</h3>
  <p>Permissions on <em><?php echo DIR_FS_CATALOG_OVERLAYS ; ?></em> can<?php echo (($fc->pnc) ? 'not' : '' ) ; ?> be changed<?php echo (($fc->pnc) ? ' (see the help section about security)' : '' ) ; ?>.</p>
<?php
  if($nozip){
?>
  <h3>Zip/ unzip status.</h3>
  <p>The zip extension is not loaded. This is required for your shop to be able to upload and unzip files. The alternative is that you can FTP files into place and they will be picked up by the overlay system. To do this when you use the themeroller at jQuery, you will get a customised zip file with a lot of css files (stylesheets) and graphics. When unzipped you get lot of folders and files. The required folder is <em>jquery-ui-1.7.2.custom/css/<u>custom-theme</u></em> that folder should be <ol><li>right clicked,</li><li>copied to your desktop,</li><li>renamed to whatever you want to call your overlay.</li><li>and FTP'd to the folder <em><?php echo DIR_FS_CATALOG_OVERLAYS ; ?></em></li></ol>
  Inside it should be stylesheets and an images folder.  If you upload the entire &quot;development bundle&quot;, then your shop will be unable to find the correct stylesheet.</p>
<?php
  }
?>

  <p><em><?php echo DIR_FS_CATALOG_OVERLAYS ; ?></em> is <?php echo (($fc->dnw) ? 'not' : '' ) ; ?> writeable so files can<?php echo (($fc->dnw) ? 'not' : '' ) ; ?> be uploaded<?php echo (($fc->dnw) ? '. Use your FTP program to change the folder to be able to upload custom overlays' : '' ) ; ?>.</p>
<?php
  if(!$fc->dnw && !$nozip){
?>
  <h3>New Overlay upload.</h3>
<?php
  if($fc->pnc){
?>
  <p><strong>Please change <em><?php echo DIR_FS_CATALOG_OVERLAYS ; ?></em> to readonly after file any uploads.</strong></p>
<?php
  }
?>
  <p>When you use the themeroller at jQuery, you will get a customised zip file with a lot of css files (stylesheets) and graphics. When unzipped you get lot of folders and files. The required folder is <em>jquery-ui-1.7.2.custom/css/<u>custom-theme</u></em> that folder should be <ol><li>renamed to your new theme name (no spaces/ special characters except for <b>_</b> <br />Example: <em> my_new_colours</em>),</li><li>right clicked,</li><li>zipped (on windows this is <em>send to <span style="font-style: normal; font-weight: bolder; color:black; background-color:#888888; ">&gt;</span> compressed folder)</em></li></ol>You can test that the zip is valid as when unzipped <em>(extracted)</em> it should be a single folder called the same as the zip file, but without the .zip ending.<br />Inside it should be stylesheets (possibly only one) and an images folder.  If the entire &quot;development bundle&quot; is uploaded then the shop will be unable to find the correct stylesheet.</p>
  <form method="post" enctype="multipart/form-data" action="overlay.php">
  <label for="nof">Zip to upload</label><input type="file" id="nof" name="nof" value="" />
  <input type="submit" value="upload" />
  </form>
<?php
  }
break;
case 'help':
?>
<div class="adminbox">
  <h2><?php echo TEXT_LINK_TEMPLATE_OVERLAY_OV ;?></h2>


  <h3><?php echo TEXT_TITLE_TEMPLATE_OVERLAY_OV ;?></h3>

  <p>Templates are where the bits of the shop are (the page layout), overlays are the colouring on top.</p>
  <p>We designed a series of stock templates so that they would be compatible with the colouring picked on the uiJquery themeroller project.</p>
  <p>This module then ships with the 25 stock themes from <a href="#uijquery">jQuery UI</a>, so with the 3 shipped themes, you then have 75 different colouring options.</p>
  <p>You can also go to uijquery.com and <em>roll your own</em>, you can pick your font-colours and backgrounds upload them and apply them to your shop.</p>
  <p>The #### is still compatible with any correctly constructed Zen Cart theme from 1.3 through to 1.3.8a, so if you have an existing shop and the theme was correctly built using the <a href="#override">override system</a>, everything will display as normal. (Some purchased themes break parts of the original zen cart, by not correctly using the override system).</p>


  <h3>Compatibility.</h3>
  <p>All shipped themes list their compatibility with the version of the jQuery UI themeroller. This was initially 1.7.2 (known as the default) and the also any custom themes built on 1.7.2. jQuery will soon move to 1.8 and we'll upgrade the page layouts and confirm the compatibility.</p>

  <h3>Security.</h3>
  <p>The overlay management system is fulling integrated with the ### security module. To upload a file the destination folder is unlocked, the files placed into position, and the the folder is relocked to read only. If the folder cannot be locked and unlocked then other advice is given how FTP can be use to use the overlay system and still remain secure.</p>

  <h4>Footnotes</h4>
  <ul style="list-style:none">
  <li><a name="uijquery"> </a>jQuery UI - stands for jQuery (a javascript set of commands and programming bits, known as a library), UI stands for User Interface.</li>
  <li><a name="override"> </a>Zen Cart is built with a system so that it's layouts remain the same and then new layouts are placed in override folders. A correctly designed layout uses this system and doesn't overwrite any files.</li>
  <li></li>
  </ul>
<?php
break;
default:
?>

<div class="adminbox">

<h3><?php echo TEXT_TITLE_TEMPLATE_OVERLAY ; ?></h3>

<p><?php echo TEXT_INFO_TEMPLATE_OVERLAY ; ?></p>

<?php
/*
foreach($template_info as $key=>$array){

print  nl2br(print_r($array, true));

}
*/
?>
<table border="0" width="100%" cellspacing="0" cellpadding="2">
                    <tr class="dataTableHeadingRow">
                      <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_LANGUAGE; ?></td>
                      <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_NAME ; ?></td>
                      <td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_COMPAT ; ?></td>
                      <td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_DIRECTORY ; ?></td>
                      <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td>
                    </tr>
<?php
  $template_query_raw = "select * from " . TABLE_TEMPLATE_SELECT;
  $template_split = new splitPageResults($_GET['page'], MAX_DISPLAY_SEARCH_RESULTS, $template_query_raw, $template_query_numrows);
  $templates = $db->Execute($template_query_raw);
  while (!$templates->EOF) {
    if ((!isset($_GET['tID']) || (isset($_GET['tID']) && ($_GET['tID'] == $templates->fields['template_id']))) && !isset($tInfo) && (substr($action, 0, 3) != 'new')) {
      $tInfo = new objectInfo($templates->fields);
    }
?>
  <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" style="cursor: default" >
<?php
//     if (isset($tInfo) && is_object($tInfo) && ($templates->fields['template_id'] == $tInfo->template_id)) {
//       echo '              <tr class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" >' . "\n";
//     } else {
//       echo '              <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" >' . "\n";
//     }
    if ($templates->fields['template_language'] == 0) {
      $template_language = "Default(All)";
    } else {
      $ln = $db->Execute("select name
                          from " . TABLE_LANGUAGES . "
                          where languages_id = '" . $templates->fields['template_language'] . "'");
      $template_language = $ln->fields['name'];
    }
?>
                    <td class="dataTableContent"><?php echo $template_language; ?></td>
                    <td class="dataTableContent"><?php echo $template_info[$templates->fields['template_dir']]['name']; ?></td>
                    <td class="dataTableContent" align="center"><?php echo return_overlay_options($templates->fields['template_dir'], $templates->fields['template_overlay']); ?></td>
                    </tr></form>
<?php
    $templates->MoveNext();
  }

?>
                    <tr>
                      <td colspan="5"><table border="0" width="100%" cellspacing="0" cellpadding="2">
                          <tr>
                            <td class="smallText" valign="top"><?php echo $template_split->display_count($template_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_GET['page'], TEXT_DISPLAY_NUMBER_OF_TEMPLATES); ?></td>
                            <td class="smallText" align="right"><?php echo $template_split->display_links($template_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_GET['page']); ?></td>
                          </tr>

                        </table></td>
                    </tr>
                  </table></td></tr>
</table>
<?php
// print nl2br(print_r($template_info, true));
// print nl2br(print_r($overlay_info, true));

	} // end of page switch

?>
	<h3 style="margin-top:10px;">License.</h3>
	<p>Licensed and distributed under the GPL version 2.<br />Copyright &copy; Philip Clarke/ Bouncing Ltd 2009</p>
</div>

</div> <!--end of clear both-->

<!-- body_eof //-->
<!-- footer //-->
<?php
	require(DIR_WS_INCLUDES . 'footer.php');
?>
<!-- footer_eof //-->
</body>
</html>
<?php
	require(DIR_WS_INCLUDES . 'application_bottom.php');